import type {SubForum} from "./Forum.ts";
import type {PageData} from "./Common.ts";
import {AnonymousUtils} from "../utils/AnonymousUtils.ts";
import {decode, unEscape} from "../utils/StrUtils.ts";
import {Timestamp, TS} from "./Timestamp.ts";
import {parseTitleFont} from "./TitleFont.ts";
import {parseTopicStatus, TopicStatus} from "./TopicStatus.ts";
import {parseReplyStatus, ReplyStatus} from "./ReplyStatus.ts";
import {ForumStatus, parseForumStatus} from "./ForumStatus.ts";
import {decodeFromUTF8, encodeToGB18030} from "../utils/encoding.ts";
import {buildReplyInfoSimple, type ReplyInfoSimple} from "./Reply.ts";

export interface TopicParent {
    forumId: number
    colTid: number | undefined
    name: string
}

export interface TopicMiscVar {
    colTid: number | undefined
    // 入口id 可能为合集ID或版面id
    entranceId: number | undefined
    forumStatus: ForumStatus[]
}

export interface TopicInfoSimple {
    topicId: number
    forumId: number
    title: string
    status: ReplyStatus[]
    authorUid: number | string | undefined
    postDatetime: Timestamp | undefined
    quoteFrom: number | undefined
}

export const buildTopicInfoSimple = (data: any): TopicInfoSimple => {
    return {
        topicId: data.tid,
        forumId: data.fid,
        title: decode(data.subject) || '',
        status: parseReplyStatus(data.type),
        authorUid: data.authorid,
        postDatetime: TS(data.postdate),
        quoteFrom: data.quote_from > 0 ? data.quote_from : undefined,
    }
}

export interface TopicInfo extends TopicInfoSimple {
    authorName: string | undefined
    lastModify: Timestamp | undefined
    lastPost: Timestamp | undefined
    lastPosterName: string | undefined
    topicParent: TopicParent | undefined
    recommendScore: number | undefined
    replies: number | undefined
    colTid: number | undefined
    topicMiscVar: TopicMiscVar
    reply: ReplyInfoSimple | undefined
    topicStatus: TopicStatus[] | undefined
    punishedUserId: number[] | undefined

    reversed: boolean,
    // 评分主题
    scoreTopic: boolean,
    down: boolean,

    colTopic: TopicInfo | undefined

    totalPage: number | undefined
    // 收藏ID 用于从收藏夹中移除主题或回复
    favorId: string
    entranceType: 'topic' | 'forum' | 'col'
    entranceId: number | undefined

    // 是否被屏蔽
    blocked?: boolean | undefined
}


export interface TopicListData extends PageData<TopicInfo> {
    forumId: number | undefined
    forumName: string
    colTid: number | undefined
    colName: string | undefined
    toppedTopicId: number | undefined
    subForums: SubForum[] | undefined
}

const buildSubForums = (data: any): SubForum[] => {
    return data ? Object.keys(data).map(key => {
        const item = data[key]
        const type = key.startsWith('t') ? 'col' : 'forum'
        const id = item[0] as number
        const name = item[1] as string
        const mirrorId = item[3] as number
        const status = parseForumStatus(item[4] as number)

        return {type, id, name, mirrorId, status}
    }) : []
}
export const buildTopicInfo = (data: any): TopicInfo => {
    const simple = buildTopicInfoSimple(data)
    const tStatus = (data.topic_misc_var && data.topic_misc_var[1]) ? parseTopicStatus(data.topic_misc_var[1]) : []
    const titleFont = parseTitleFont(data.topic_misc);
    const topicStatus = [...tStatus, ...(titleFont.topicStatus || [])];
    const topicMiscVar = {
        colTid: data.topic_misc_var && data.topic_misc_var[2],
        entranceId: data.topic_misc_var && data.topic_misc_var[3],
        forumStatus: data.topic_misc_var && data.topic_misc_var[1] ? parseForumStatus(data.topic_misc_var[1]) : []
    } as TopicMiscVar

    // 所属合集
    const colTopic = (() => {
        if (!data.__ST) return undefined
        const info = buildTopicInfo(data.__ST)
        info.title = decodeFromUTF8(encodeToGB18030(info.title))
        return info
    })()
    const scoreTopic = topicStatus.includes(TopicStatus.REVERSED_1) && topicStatus.includes(TopicStatus.REVERSED_2)
    const reply = data.__P ? buildReplyInfoSimple(data.__P) : undefined;
    const punishedId = data.post_misc_var?.[16]?.toString();
    return {
        ...simple, colTopic,
        punishedUserId: punishedId ? punishedId?.split(',')?.map(Number) : undefined,
        authorName: AnonymousUtils.transform(unEscape(data.author)),
        lastModify: TS(data.lastmodify),
        lastPost: TS(data.lastpost),
        lastPosterName: data.lastposter,
        topicParent: data.parent ? {
            forumId: Number(data.parent[0]),
            colTid: data.parent[1],
            name: data.parent[2],
        } : undefined,
        recommendScore: data.recommend,
        replies: data.replies,
        colTid: titleFont.colTid,
        topicStatus: topicStatus,
        scoreTopic,
        reversed: topicStatus.includes(TopicStatus.REVERSED),
        down: simple.status.includes(ReplyStatus.DOWN) || topicStatus.includes(TopicStatus.DOWN),
        topicMiscVar,
        reply,
        totalPage: parseInt(String((data.replies + 1) / 20)),

        favorId: reply ? `${simple.topicId}_${reply.replyId}` : simple.topicId.toString(),
        entranceType: simple.status.includes(ReplyStatus.IS_SET) ? 'col' : simple.status.includes(ReplyStatus.IS_FORUM) ? 'forum' : 'topic'
        ,
        entranceId: simple.quoteFrom || topicMiscVar.entranceId || simple.topicId,
    }
}
export const buildTopicListData = (data: any): TopicListData => {
    return {
        forumId: data.__F.fid,
        forumName: data.__F.name,
        colTid: data.__F.set_topic_tid,
        colName: data.__F.set_topic_subject,
        toppedTopicId: data.__F.topped_topic,
        subForums: buildSubForums(data.__F.sub_forums),
        data: data.__T.map(buildTopicInfo),
        total: Number(data.__ROWS),
        size: Number(data.__T__ROWS_PAGE),
        totalPage: Math.floor(data.__ROWS / data.__T__ROWS_PAGE + 1)
    }
}